/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.ProductBeanLocal;
import entities.Product;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;

/**
 *
 * @author Jesus
 */
@ManagedBean
public class ProductViewBean {

    @EJB
    private ProductBeanLocal productBean;
    private Product product;
    private int quantity;
    @ManagedProperty(value = "#{cartBean}")
    private CartBean cart;
    @ManagedProperty(value = "#{param.product}")
    private String paramValue;

    public ProductViewBean() {
        if (quantity < 1) {
            quantity = 1;
        }

    }

    @PostConstruct
    public void init() {
        if (paramValue != null) {
            product = productBean.findById(Long.parseLong(paramValue));
        }
    }

    public String addToCart() {
        Product selectedProduct = productBean.findById(Long.parseLong(paramValue));
        if (cart == null) {
            cart = new CartBean();
        }
        cart.addProduct(selectedProduct, quantity);
        FacesContext.getCurrentInstance().addMessage(
                null, new FacesMessage(
                FacesMessage.SEVERITY_INFO,
                "Has añadido al carrito " + quantity + " unidades de " + product.getName() + ".", ""));
        return "main";
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public CartBean getCart() {
        return cart;
    }

    public void setCart(CartBean cart) {
        this.cart = cart;
    }

    public String getParamValue() {
        return paramValue;
    }

    public void setParamValue(String paramValue) {
        this.paramValue = paramValue;
    }
}
